package com.krtech.wecard.module.sys.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.krtech.wecard.framework.exception.BusinessException;
import com.krtech.wecard.framework.model.CommRes;
import com.krtech.wecard.framework.model.ResultTable;
import com.krtech.wecard.framework.model.ResultTree;
import com.krtech.wecard.framework.utils.LoginUtil;
import com.krtech.wecard.module.sys.entity.DeptOperateLog;
import com.krtech.wecard.module.sys.entity.SysDept;
import com.krtech.wecard.module.sys.entity.SysSchoolInfo;
import com.krtech.wecard.module.sys.entity.SysUser;
import com.krtech.wecard.module.sys.pojo.SysDeptVo;
import com.krtech.wecard.module.sys.service.DeptOperateLogService;
import com.krtech.wecard.module.sys.service.SysDeptService;
import com.krtech.wecard.module.sys.service.SysSchoolInfoService;
import com.krtech.wecard.utils.TreeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author laker
 * @since 2021-08-11
 */
@RestController
@RequestMapping("/sys/dept")
@Api(tags = "部门管理")
public class SysDeptController {
    @Autowired
    SysDeptService sysDeptService;

    @Autowired
    private DeptOperateLogService deptOperateLogService;

    @Autowired
    private SysSchoolInfoService schoolInfoService;

    @GetMapping
    @ApiOperation(value = "分页查询")
    public CommRes pageAll(@RequestParam(required = false, defaultValue = "1") long current,
                           @RequestParam(required = false, defaultValue = "10") long size) {
        Page roadPage = new Page<>(current, size);
        LambdaQueryWrapper<SysDept> queryWrapper = new QueryWrapper().lambda();
        Page pageList = sysDeptService.page(roadPage, queryWrapper);
        return CommRes.ok(pageList);
    }

    @PostMapping
    @ApiOperation(value = "新增或者更新")
    public CommRes saveOrUpdate(@RequestBody SysDept param) {
        SysDept sysDept = sysDeptService.mySaveOrUpdate(param);
        return CommRes.ok(sysDept);
    }

    @PostMapping("saveOrUpdateBatch")
    @ApiOperation(value = "批量新增或者更新")
    public CommRes saveOrUpdateBatch(@RequestBody List<SysDept> sysDeptList) {
        List<SysDept> collect = sysDeptList.stream().map(param -> {
            SysDept sysDept = sysDeptService.mySaveOrUpdate(param);
            return sysDept;
        }).collect(Collectors.toList());
        return CommRes.ok(collect);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询")
//    @SaCheckPermission("dept.detail")
    public CommRes get(@PathVariable Long id) {
        return CommRes.ok(sysDeptService.getById(id));
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "根据id删除")
//    @SaCheckPermission("dept.delete")
    public CommRes delete(@PathVariable Long id) {
        return CommRes.ok(sysDeptService.removeById(id));
    }

    @PostMapping("/deleteByCode")
    @ApiOperation(value = "根据code删除")
//    @SaCheckPermission("dept.delete")
    public CommRes deleteByCode(@RequestBody List<String>  code) {
        boolean remove = sysDeptService.remove(new QueryWrapper<SysDept>().in(SysDept.COL_CODE, code));

        return CommRes.ok(remove);
    }

    @DeleteMapping("/batch/{ids}")
    @ApiOperation(value = "根据批量删除ids删除")
//    @SaCheckPermission("dict.delete")
    public CommRes batchRemove(@PathVariable Long[] ids) {
        return CommRes.ok(sysDeptService.removeByIds(CollUtil.toList(ids)));
    }


    @GetMapping("/data")
    public ResultTable data(SysDept param) {
        List<SysDept> data = sysDeptService.list(Wrappers.<SysDept>lambdaQuery()
                .eq(SysDept::getStatus, true)
                .orderByAsc(SysDept::getSort));
        return ResultTable.dataTable(data);
    }


    @GetMapping("/tree")
    @ApiOperation(value = "部门树，无须传参数")
    public List<SysDeptVo> tree(SysDept param) {
        List<SysDept> data = sysDeptService.list(Wrappers.query(param).eq(SysDept.COL_STATUS, true)
                .orderByAsc(SysDept.COL_SORT));

        List<SysDeptVo> deptVoList = data.stream().map(one -> {
            SysDeptVo sysDeptVo = new SysDeptVo();
            BeanUtil.copyProperties(one, sysDeptVo);
            return sysDeptVo;
        }).collect(Collectors.toList());

        //todo 考虑不传入pid
//        Long pid = 0L;
//        if (param.getPid() != null){
//            pid = param.getPid();
//        }
        String pcode = "";
        if (StrUtil.isNotEmpty(param.getPcode())){
            pcode = param.getPcode();
        }

        List<SysDeptVo> tree = TreeUtil.DepttoTreeByPcode(deptVoList, pcode);
        return tree;
    }

}